package com.yidian.service.impl;

import com.yidian.common.constant.QinuiConstant;
import com.yidian.common.constant.SmsConstant;
import com.yidian.common.entity.Result;
import com.yidian.common.utils.QinuiUtils;
import com.yidian.common.utils.RedisUtils;
import com.yidian.dto.LoginDto;
import com.yidian.entity.Channel;
import com.yidian.entity.User;
import com.yidian.entity.UserExample;
import com.yidian.mapper.UserMapper;
import com.yidian.service.UserService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private UserServiceImpl userService;


    /**
     * 发送短信验证码
     *
     * @param telephone
     * @param authCode
     * @return
     */
    @Override
    public Result sendSms(String telephone, String authCode) {
        //调用工具类发送短信
        // String info = com.itheima.utils.SmsUtils.send(telephone,"签名","模板code",authCode);
        String info = "OK";
        Result resultInfo = new Result();
        //判断发送结果
        if ("OK".equals(info)) {
            //把验证码放到Redis
            //设置60s
            redisUtils.set(SmsConstant.SMS_CODE + telephone, authCode);
            //发送成功
            resultInfo.setFlag(true);
            resultInfo.setMessage("发送成功");
        } else {
            resultInfo.setFlag(false);
            resultInfo.setMessage("发送失败");
        }
        return resultInfo;
    }

    @Override
    public List<User> selectByExample(LoginDto loginDto) {
        //通过手机号查询用户对象
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andPhoneEqualTo(loginDto.getTelephone());
        return userMapper.selectByExample(userExample);
    }

    /**
     * 根据用户ID获取用户信息
     *
     * @param userId
     * @return
     */
    @Override
    public User selectByUserId(Long userId) {

        return userMapper.selectByPrimaryKey(userId);
    }

    /**
     * 用户注册
     *
     * @param loginDto
     * @return
     */
    @Override
    public Result register(LoginDto loginDto) {


        //1判断验证码是否过期
        String code = redisUtils.get(SmsConstant.SMS_CODE + loginDto.getTelephone());
        if (code == null) {
            return Result.fail("验证码过期", null);
        }
        //2.判断验证码是否相等
        else if (!loginDto.getCode().equals(code)) {
            return Result.fail("验证码错误", null);
        }

        //3.验证码没问题进行注册并登陆
        User newUser = new User();
        newUser.setPhoto("http://r47o75nkk.hn-bkt.clouddn.com/c2daef5a-1bbd-46aa-8893-77a95cbd41be2.jpg");
        newUser.setPhone(loginDto.getTelephone());
        userMapper.insertSelective(newUser);

        List<User> user = userService.selectByExample(loginDto);

        return Result.ok("ok",user.get(0));
    }

    /**
     * 用户登录
     *
     * @param loginDto
     * @return
     */
    @Override
    public Result login(LoginDto loginDto, User user) {

        //判断验证码是否正确
        String smsCode = loginDto.getCode();
        //从Redis中获取验证码
        String code = (String) redisUtils.get(SmsConstant.SMS_CODE + loginDto.getTelephone());
        if (code == null) {
            //如果Redis中验证码为空，则提示验证码过期
            return Result.fail("验证码过期", null);
        }
        else if (!smsCode.equals(code)) {
            //不相等则提示验证码错误
            return Result.fail("验证码错误", null);
        } else {
            //5.返回登录成功
            return Result.ok("登录成功", user);
        }
    }


    @Override
    /**
     * 根据用户ID查询该用户的频道信息
     */
    public List<Channel> selectChannelByUserId(long id) {
        return userMapper.selectChannelByUserId(id);
    }

    /**
     * 关注用户
     *
     * @param upId 被关注者的ID
     * @param id   当前用户ID
     * @return
     */
    @Override
    public int addFollow(long upId, long id) {
        return userMapper.addFollow(upId, id);
    }

    /**
     * 取消关注
     *
     * @param id 被关注人的ID
     * @return
     */
    @Override
    public int deleteFollow(long upId, long id) {
        return userMapper.deleteFollow(upId, id);
    }

    /**
     * 根据id查询指定用户信息
     *
     * @param id 指定用户id
     * @return
     */
    @Override
    public User selectByPrimaryKey(Long id) {
        return userMapper.selectByPrimaryKey(id);
    }


    /**
     * 根据用户更新用户信息
     *
     * @param user
     * @return
     */
    public int updateUserByUserId(User user) {
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(user.getId());
        return userMapper.updateByExampleSelective(user, example);
    }

    /**
     * 根据用户更新用户图片
     *
     * @param user
     * @return
     */
    @SneakyThrows
    @Override
    public int updatePhotoByUserId(long id, MultipartFile imgFile) {
        // 获取原始文件名
        String originalFilename = imgFile.getOriginalFilename();
        int lastIndexOf = originalFilename.lastIndexOf(".");
        // 获取文件houzhui
        String suffix = originalFilename.substring(lastIndexOf - 1);
        // 使用UUID随机生成文件名，防止同名文件覆盖
        String filename = UUID.randomUUID().toString() + suffix;
        QinuiUtils.upload2Qiniu(imgFile.getBytes(), filename);
        // 图片上传成功
        String photoUrl = QinuiConstant.QINUI_URL_PREFIX + filename;

        //获取当前用户
        User user = userMapper.selectByPrimaryKey(id);

        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(id);

        user.setPhoto(photoUrl);

        return userMapper.updateByExampleSelective(user, example);
    }


}
